package io.github.annyylxyms.gyncache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * plugin entrypoint(插件集合点)
 * 这么写的优势是统一管理：只要添加了GynPlugin接口的类，就会自动被spring管理，并加入到plugins里
 */
@Component
public class GynApplicationListener implements ApplicationListener {
    @Autowired
    List<GynPlugin> plugins;

    /**
     * ApplicationReadyEvent相当于之前的启动完成的ApplicationRunner，这两个事件在spring生命周期里是挨着的
     * ContextClosedEvent相当于之前用过的predestroy，但是这个事件是spring关闭时触发的,这两个也相当于是等价的
     * @param event
     */
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent are) {
            for (GynPlugin plugin : plugins) {
                plugin.init();
                plugin.startup();
            }
        } else if (event instanceof ContextClosedEvent cce) {
            for (GynPlugin plugin : plugins) {
                plugin.shutdown();
            }
        }
    }
}
